<?php

include_once INDEX_PATH . '/../application/modules/Store/forms/Search.php';

class Store_ProductController extends YouNet_Controller_Action
{

	/**
	 * Id of Store
	 * @var int
	 */
	private $_id_store = 0;

	/**
	 * Id of Product
	 * @var int
	 */
	private $_id;

	/**
	 *
	 * @var Core_Model_Store
	 */
	private $_store = null;

	public function preDispatch()
	{
		parent::preDispatch();
		$this->_id_store = $this->_getParam('id_store', 0);
		$this->_id = $this->_getParam('id', 0);
		$this->_store = Core_Model_DbTable_Stores::getStoreByUser($this->_id_store, $this->_user);
		$this->view->store = $this->_store;
		$this->view->render('store/select_fanpages.phtml');
		$this->view->use_admin_menu = true;
		if (!empty($this->_store))
		{
			$this->view->id_store = $this->_store->id;
		}
        
        $this->view->new_orders = $this->_store->getNumberNewOrders();
	}

	/**
	 *
	 * @staticvar string $form
	 * @return Store_Form_Product
	 */
	private function _getForm()
	{
		static $form = null;
		if (!($form instanceof YouNet_Form))
		{
			$arrOptions = array(
				'store' => $this->_store
			);
			if ($this->_id)
			{
				$arrOptions['product'] = $this->_store->getProduct($this->_id);
			}
			$form = new Store_Form_Product($arrOptions);
			$form->setCancelUrl($this->_getBackUrl());
			$this->view
					->headScript()
					->prependFile(REPOSITORY_URL . '/javascript/tiny_mce/jquery.tinymce.js');
		}
		return $form;
	}

	/**
	 * This action is the first view when accessing the app
	 */
	public function indexAction()
	{
		
	}

	/**
	 *
	 */
	public function listAction()
	{
		$params = array();
		$page = $this->_getParam('page', 1);
		$arrSort = $this->_getParam('sort', array());

		$form = new Store_Form_Search(array('store' => $this->_store));
		$form->setMethod('get');
		$form->setAction($this->view->url(array('page' => null)));

		if (!empty($_GET) && $form->isValid($_GET))
		{
			$params = $form->getValidValues($_GET);
		}

		$paginator = $this->_store->findProductsBelongToStore($params, $page, $arrSort);
		//View        
		$this->view->messages = $this->_helper->flashMessenger->getMessages();
		$this->view->paginator = $paginator;
		$this->view->form = $form;
		$this->view->pageValues = $params;
		$this->view->url = '#';
	}

	public function createAction()
	{
		$form = $this->_getForm();
		if (isset($_POST['form_submitted']))
		{
			if ($form->isValid($_POST))
			{
				$arrImages = $form->getProductImageNames();
				$arrValues = $form->getValidValues($_POST);
				$product = $this->_store->createProductFromParams($arrValues, $arrImages);
				$this->_id = $product->id;

				$message = $this->translate('MSG_CREATE_PRODUCT_SUCCESSFUL');
				$message .= $this->_getListFanpages();

				$this->_helper->flashMessenger->addMessage($message);
				$this->disableAutoRender();
				Core_Util::redirect($this->view->url(array('action' => 'list', 'page' => 1)));
				return;
			}
		}
        $this->view->form_header = 'HEADER_CREATE_NEW_PRODUCT';
		$this->view->form = $form;
		$this->render('form');
	}

	public function createCategoryAction()
	{
		$this->disableAutoRender();
		$row = $this->_store->createCategoryFromParams($this->_params);
		if (!empty($row))
		{
			echo Zend_Json::encode($row->toArray());
		}
	}

	public function editAction()
	{
		$form = $this->_getForm();

		$data = $this->_store->getProduct($this->_id);

		if (empty($data))
		{
			$flashMessage = $this->translate('BACKEND_WARNING_NOTFOUND_PRODUCT');
			$this->_helper->flashMessenger->addMessage($flashMessage);
			return Core_Util::redirect($this->view->url(array('controller' => 'product', 'action' => 'list', 'module' => 'store', 'id_store' => $this->_store->id), '', true));
		}

		$form->fill($data);

		if (isset($_POST['form_submitted']))
		{
			if ($form->isValid($_POST))
			{
				$arrImages = $form->getProductImageNames();
				$arrValues = $form->getValidValues($_POST);
				$this->_store->updateProductFromParams($this->_id, $arrValues, $arrImages);

				$message = $this->translate('MSG_EDIT_PRODUCT_SUCCESSFUL');
				$message .= $this->_getListFanpages();

				$this->_helper->flashMessenger->addMessage($message);
				$this->_redirectBack();
				return;
			}
		}
        $this->view->form_header = 'HEADER_EDIT_PRODUCT';
		$this->view->form = $form;
		$this->render('form');
	}

	private function _getListFanpages()
	{
		$message = '';

		if (!$this->_store->isShown())
		{
			return '';
		}

		$arrListPages = $this->_store->getListPages();
		$product = Core_Model_DbTable_Products::getInstance()->findOne($this->_id);

		if (empty($product))
		{
			return '';
		}
		else
		{
			if ($product->status != Core_Model_DbTable_Products::STATUS_SHOWN)
			{
				return '';
			}
		}

		if (sizeof($arrListPages) > 0)
		{
			$listPages = array();
			foreach ($arrListPages as $page)
			{
				$listPages[] = sprintf('<a target="_blank" href="%s">%s</a>', $this->_social->pageUrl(array('target' => 'detail', 'id_product' => $this->_id), $page->id_page), Core_Util::standardizePageName($page->name));
			}
			$message = '<br/>';
			$message .= $this->translate('MSG_VIEW_PRODUCT_AT_FANPAGE');
			$message .= implode(', ', $listPages);
		}
		return $message;
	}

	/**
	 * Change product status from `hide` to `shown`
	 */
	public function hideAction()
	{
		if ($this->_id)
		{
			$this->_store->hideProduct($this->_id);
		}
		$this->_helper->flashMessenger->addMessage($this->translate('MSG_HIDE_PRODUCT_SUCCESSFULLY'));
		//Redirect back
		$this->_redirectBack();
	}

	/**
	 * Change product status from `shown` to `hide`
	 */
	public function showAction()
	{
		if ($this->_id)
		{
			$this->_store->showProduct($this->_id);
		}
		$this->_helper->flashMessenger->addMessage($this->translate('MSG_SHOW_PRODUCT_SUCCESSFULLY'));
		//Redirect back
		$this->_redirectBack();
	}

	public function deleteAction()
	{
		if ($this->_id)
		{
			if ($this->_store->deleteProduct($this->_id))
			{
				$this->_helper->flashMessenger->addMessage($this->translate('MSG_DELETED_SUCCESSFULLY'));
			}
		}
		//Redirect back
		$this->_redirectBack();
	}

	public function getSystemCategoriesAction()
	{
		$this->disableAutoRender();
		$arrCategories = array();
		$id_parent = $this->_getParam('id_parent', 0);
		if ($id_parent)
		{
			$arrCategories = Core_Model_DbTable_Category_Systems::getArrCategories($id_parent);
		}
		echo Zend_Json_Encoder::encode($arrCategories);
	}

	public function getCustomCategoriesAction()
	{
		$this->disableAutoRender();
		$arrCategories = array();
		$id_parent = $this->_getParam('id_parent', 0);
		if ($id_parent)
		{
			$arrCategories = $this->_store->getArrCategories($id_parent);
		}
		echo Zend_Json_Encoder::encode($arrCategories);
	}

	private function _redirectBack()
	{
		$this->disableAutoRender();
		$this->_helper->redirector->gotoUrl($this->_getBackUrl(), array('prependBase' => false));
	}

	private function _getBackUrl()
	{
		$backLink = $this->_getParam('back_link');
		if ($backLink != '')
		{
			$link = base64_decode($backLink);
			return urldecode($link);
		}
		return $this->view->url(array('action' => 'list', 'id' => null));
	}
}